import {useEffect, useRef, createRef, useState,useCallback} from "react";
import {Item1} from "../use-context"

export default function UseRefDemo(){
    let [count, setCount] = useState(0);
    let [index,setIndex] = useState(0);
    //测试 useRef 和 createRef 的区别
    var ref = useRef(null);
    var refFromCreate = createRef();
    var refFromUse = useRef(1);
    console.log("ref:");
    console.log(ref);
    // var domRef = useRef(0);
    var domRef = null;
    let timer = useRef(null);
    let timer1;

    if(!refFromCreate.current) {
        refFromCreate.current = index;
    }

    if(refFromUse.current){
        refFromUse.current = index;
    }

    useEffect(()=>{
        let id = setInterval(()=>{
            setCount(count=>count+1);
        },1000);
        timer.current = id;
        timer1 = id;
        return ()=>{
            clearTimeout(timer.current);
        }
    });

    var onClickRef = useCallback(function(){
        console.log("timer.current:");
        console.log(timer.current);
        clearInterval(timer.current);
        console.log("domRef:");
        console.log(domRef);
    },[])

    var onClick = useCallback(()=>{
        console.log(ref.current);
        clearInterval(timer1);
    },[]);
    
    var setRenderIndex = function(e){
        setIndex(prev=>prev+1);
    }
    return (
        <div>
            <p>Current render index:</p>
            <p>refFromCreate:{refFromCreate.current}</p>
            <p>refFromUse:{refFromUse.current}</p>
            <div>
                <button onClick={setRenderIndex}>set index</button>
            </div>
            点击次数: {count}<br/>
            <Item1 ref={ref}/>
            <div ref={domRef}>useRef 可以用于 DOM 吗?</div>
            <button onClick={onClick}>click ref</button>
            <button onClick={onClickRef}>on click ref(useRef)</button>
        </div>
    );
}
